<template>
    <div>
        <a-modal v-model:visible="modalVisible" title="自定义端口" @ok="handleOk" :confirm-loading="confirmLoading">
            <div>
                <div class="mb-8">通过自定义服务可以暴露端口到公网进行访问，只需将服务在实例中指定端口启动即可</div>
                <div class="mb-8">
                    <div class="mb-8">TCP端口</div>
                    <div v-if="domainList.length">
                        <div class="domainList" v-for="(item, index) in domainList" :key="index">
                            <div>内部端口：{{ item.local_port }}</div>
                            <div>外部端口: {{ item.proxy_port }}</div>
                        </div>
                    </div>
                </div>
                <a-form ref="formRef" name="dynamic_form_item" :model="form" v-if="!domainList.length">
                    <a-form-item v-for="(domain, index) in form.domains" :key="domain.key" label="TCP端口"
                        :name="['domains', index, 'value']" :rules="{
                            required: true,
                            message: '请输入端口',
                            trigger: 'change',
                        }">
                        <a-input v-model:value="domain.value" placeholder="请输入端口" style="width: 60%; margin-right: 8px" />
                        <minus-square-outlined v-if="form.domains.length > 1" class="dynamic-delete-button"
                            :disabled="form.domains.length === 1" @click="removeDomain(domain)" />
                    </a-form-item>
                    <a-form-item>
                        <a-button type="dashed" @click="addDomain" :disabled="formatDisabled()">
                            <PlusOutlined />
                            添加端口配置
                        </a-button>
                    </a-form-item>

                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { defineProps, defineEmits, computed, ref, reactive } from 'vue';
import { handleInstance } from 'api/modules/api.instance'
import { XsyMessage } from '@/libs/util.toast'
import { MinusSquareOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { storeToRefs } from 'pinia'
import userInfoStore from '@/stores/userInfo.js'
const useUserInfoStore = userInfoStore()
const { userInfo } = storeToRefs(useUserInfoStore);

const props = defineProps({
    modelValue: {
        type: Boolean,
    },
    instance: {
        type: Object,
        default: {}
    }
});

const form = ref({
    domains: []
})

const domainList = ref([])
domainList.value = props?.instance?.InstancePhysicalState?.toolsAttrsUrl?.custom || []

const emit = defineEmits(['update:modelValue', 'handelOpt']);
const modalVisible = computed({
    get: () => props.modelValue,
    set: v => emit('update:modelValue', v),
});

// 确定按钮的回调
const confirmLoading = ref(false)
const handleOk = () => {
    if (domainList.value.length) {
        emit('update:modelValue', false)
        return false
    }

    formRef.value.validateFields().then(() => {
        // 自定义添加的端口
        let customPort = form.value.domains.map(item => item.value)
        if ((new Set(customPort)).size != customPort.length) {
            XsyMessage.error('请勿添加相同的端口')
            return false
        }

        const params = {
            instanceId: props.instance?.Instance?.instanceId,
            method: 'reset',
            subject: 'custom_port',
            customPort
        }
        confirmLoading.value = true
        handleInstance(params).then(res => {
            confirmLoading.value = false
            if (res.code == 0) {
                emit('update:modelValue', false)
                emit('handelOpt', props.instance?.Instance?.instanceId)
            }
        }).catch(() => {
            confirmLoading.value = false
        })
    })
};

const formRef = ref();
const removeDomain = item => {
    let index = form.value.domains.indexOf(item);
    if (index !== -1) {
        form.value.domains.splice(index, 1);
    }
};
const addDomain = () => {
    form.value.domains.push({
        value: '',
        key: Date.now(),
    });
};

// 个人只有一个端口，企业可以3个
const formatDisabled = () => {
    if (userInfo?.value?.userItem?.isEnterprise) {
        if (form.value.domains.length > 3) {
            return true
        }
    } else {
        if (form.value.domains.length >= 1) {
            return true
        }
    }
    return false
}

</script>

<style lang="scss" scoped> .domainList {
     display: flex;

     div {
         flex: 1;
     }
 }
</style>

